using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;

namespace VotingSystem.Models
{
    public class Survey
    {
        [Key]
        public int Id { get; set; }

        [Required]
        [StringLength(200)]
        public string Title { get; set; } = string.Empty;

        [StringLength(1000)]
        public string? Description { get; set; }

        [Required]
        public DateTime CreatedAt { get; set; }

        public DateTime? EndTime { get; set; }

        public bool IsPublic { get; set; } = true;

        public bool IsAnonymous { get; set; }

        public bool RequireLogin { get; set; } = true;

        public bool IsActive { get; set; } = true;

        public bool AllowMultipleSubmissions { get; set; } = true;

        [Required]
        public string CreatorId { get; set; } = string.Empty;

        [ForeignKey("CreatorId")]
        public ApplicationUser? Creator { get; set; }

        public string? AccessToken { get; set; }

        public virtual ICollection<SurveyQuestion> Questions { get; set; } = new List<SurveyQuestion>();

        public virtual ICollection<SurveyResponse> Responses { get; set; } = new List<SurveyResponse>();

        public bool IsEnded => EndTime.HasValue && DateTime.Now >= EndTime.Value;

        public int TotalResponses => Responses.Count;

        public bool CanRespond(string? userId)
        {
            if (!IsActive) return false;
            if (IsEnded) return false;
            if (RequireLogin && string.IsNullOrEmpty(userId)) return false;
            if (string.IsNullOrEmpty(userId)) return true;
            
            // Check if user has already submitted and multiple submissions are not allowed
            if (!AllowMultipleSubmissions && userId != null)
            {
                return !Responses.Any(r => r.RespondentId == userId);
            }
            
            return true;
        }

        public Survey()
        {
            Questions = new List<SurveyQuestion>();
            Responses = new List<SurveyResponse>();
            CreatedAt = DateTime.Now;
        }
    }
} 